package com.googlecode.cswish.struts.conversion;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.util.StrutsTypeConverter;

public class NumberConverter extends StrutsTypeConverter {
	
	@Override
	protected Object performFallbackConversion(Map context, Object o, Class toClass) {
		if (o instanceof Enum) {
			return ((Enum)o).ordinal();
		} else {
			return super.performFallbackConversion(context, o, toClass);
		}
    }
	
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Object val = null;
		if (values != null && values.length > 0) {
			String value = values[0];
			if (value.length() > 0) {
				String str = StringUtils.remove(values[0], ',');
				if (Integer.class.equals(toClass)) {
					val = new Integer(str);
				} else if (Long.class.equals(toClass)) {
					val = new Long(str);
				} else if (BigDecimal.class.equals(toClass)) {
					val = new BigDecimal(str);
				} else if (Float.class.equals(toClass)) {
					val = new Float(str);
				} else if (Double.class.equals(toClass)) {
					val = new Double(str);
				}
			}
		}
		return val;
	}

	@Override
	public String convertToString(Map context, Object o) {
		String val;
		if (o != null) {
			val = o.toString();
		} else {
			val = null;
		}
		return val;
	}
}
